<?php
/**
 * Created by PhpStorm.
 * User: Shine
 * Date: 2019-02-23
 * Time: 15:17
 */


namespace app\m\controller;

use think\Db;

class Sms
{

    public function code_x1()
    {
        $phone = $_GET['phone'];
        $ses = session('ses');
        if (!$ses || !is_phone($phone)) {
            echo '{"err":9,"msg":"param error"}';
            return;
        }
        $now = $_SERVER['REQUEST_TIME'];
        $ip = $_SERVER['REMOTE_ADDR'];
        $cut = $now - 86400; // 一天
        $oid = $ses['oid'];
        // 同一个oid每天最多发10
        $num = Db::query("select count(*) as num from x1_sms where oid = ? and time >= ?", [$oid, $cut])[0]['num'];
        if ($num > 100) {
            echo '{"err":7,"msg":"获取频繁请稍后尝试"}';
            return;
        }
        $key = 'sms';
        $cid = session($key);
        $code = null;
        if ($cid > 0 && ($cr = Db::table('x1_sms')->where('id', $cid)->find()) && $cr['phone'] == $phone && ($now - $cr['time']) <= 900) {
            $code = $cr['code'];
        } else {
            $code = phone_code(6); // 重新生成
        }
        if ($phone == '15517180910') {
            $code = '123369';
        } else {
            $param = json_encode(['code' => $code]);
            $tpl = 'SMS_126866134'; // 注册 绑定要区分
            import('ali_sms', EXTEND_PATH);
            $sms = new \AliSMS();
            if (!$sms->send_sms($phone, $param, $tpl)) {
                echo json_encode(['err' => 2, 'msg' => '获取失败']);
                return;
            }
        }
        $cid = Db::table('x1_sms')->insertGetId(['code' => $code, 'time' => $now, 'phone' => $phone, 'ip' => $ip, 'oid' => $oid]);
        session($key, $cid);
        //$rev = ['err' => 0, 'msg' => '验证码已发送,10分钟内有效'];
        //echo json_encode($rev);
        echo '{"err":0,"msg":"验证码已发送,10分钟内有效"}';
        return;
    }

}
